package com.zhong.thesimpleconnection.action;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMContactListener;
import com.hyphenate.chat.EMClient;
import com.zhong.bmob.inter.IFindRequestAddFriendsMessageDown;
import com.zhong.bmob.inter.ISaveDown;
import com.zhong.bmob.inter.IUpdate;
import com.zhong.bmob.model.AddFriendsMessage;
import com.zhong.bmob.server.FindRequestAddFriendsMessage;
import com.zhong.bmob.server.Save;
import com.zhong.bmob.server.Update;
import com.zhong.thesimpleconnection.R;
import com.zhong.thesimpleconnection.util.EMClientHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import cn.bmob.v3.exception.BmobException;

/**
 * Created by 俊峰 on 2017/5/27.
 */

public class AddFriendsActivity extends AppCompatActivity implements View.OnClickListener, ISaveDown, IFindRequestAddFriendsMessageDown, IUpdate {

    private EditText mEditTextName;
    private EditText mEditTextReason;
    private ListView mListView;
    private TextView mTextViewCancel;
    private TextView mTextViewSend;
    private List<String> MyUserName;
    private Map<String, String> request = new HashMap<>();
    private ArrayAdapter<String> mAdapter;
    private String mUserName;
    private String mReason;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_friends);
        EMClient.getInstance().contactManager().setContactListener(new EMContactListener() {
            @Override
            public void onContactAdded(String s) {
                //好友请求被同意
            }

            @Override
            public void onContactDeleted(String s) {
                //好友请求被拒绝
            }

            @Override
            public void onContactInvited(String s, String s1) {
                //收到好友邀请
                request.put(s, s1);
                Log.d("main", "收到好友邀请");
                refresh(s);
            }

            @Override
            public void onFriendRequestAccepted(String s) {
                //被删除时回调此方法
            }

            @Override
            public void onFriendRequestDeclined(String s) {
                //增加了联系人时回调此方法
            }
        });
        initView();
        setListener();
//        Map<String, String> request = EMClientHelper.getInstance().getFriendsRequest();
        MyUserName = new ArrayList<>();
        if (!request.isEmpty()) {
            Set<String> strings = request.keySet();
            for (String string : strings) {
                MyUserName.add(string);
            }
        }
        mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, MyUserName);
        mListView.setAdapter(mAdapter);
    }

    private void refresh(String UserName) {
        if (!MyUserName.contains(UserName)) {
            MyUserName.add(UserName);
            mAdapter.notifyDataSetChanged();
        }
    }

    private void setListener() {
        mTextViewSend.setOnClickListener(this);
        mTextViewCancel.setOnClickListener(this);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final String key = MyUserName.get(position);
                String UserNameRequestReason = request.get(key);
                new AlertDialog.Builder(AddFriendsActivity.this).setTitle(key+getResources().getString(R.string.add_chat_friends_text))
                        .setMessage(UserNameRequestReason)
                        .setPositiveButton(getResources().getString(R.string.add_chat_friends_accept), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                MyUserName.remove(key);
                                request.remove(key);
                                EMClientHelper.getInstance().agreeFriendsRequest(key);
                                mAdapter.notifyDataSetChanged();
                            }
                        })
                        .setNegativeButton(getResources().getString(R.string.add_chat_friends_refuse), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                MyUserName.remove(key);
                                request.remove(key);
                                EMClientHelper.getInstance().refuseFriendsRequest(key);
                                mAdapter.notifyDataSetChanged();
                            }
                        }).show();
            }
        });
    }

    private void initView() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.AddChatFriends_Toolbar);
        mEditTextName = ((EditText) findViewById(R.id.AddChatFriends_UserName));
        mEditTextReason = ((EditText) findViewById(R.id.AddChatFriends_Reason));
        mTextViewCancel = ((TextView) findViewById(R.id.AddChatFriends_Cancel));
        mTextViewSend = ((TextView) findViewById(R.id.AddChatFriends_Send));
        mListView = ((ListView) findViewById(R.id.AddChatFriends_List_Request));
        setSupportActionBar(toolbar);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.AddChatFriends_Send:
                mUserName = mEditTextName.getText().toString();
                mReason = mEditTextReason.getText().toString();
                EMClientHelper.getInstance().getFriends(mUserName, mReason);
                mEditTextName.setText("");
                mEditTextReason.setText("");
                doThing(mUserName, mReason);
                break;
            case R.id.AddChatFriends_Cancel:
                mEditTextName.setText("");
                mEditTextReason.setText("");
                break;
            default:
                break;
        }
    }

    private void doThing(String UserName, String Reason) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                FindRequestAddFriendsMessage.findRequestAddFriendsMessage(EMClient.getInstance().getCurrentUser(), UserName, AddFriendsActivity.this);
            }
        }).start();
    }

    @Override
    public void saveSuccess() {
        Toast.makeText(this, getResources().getString(R.string.add_chat_friends_remind_me), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void saveFailed(BmobException e) {
        int code = e.getErrorCode();
        String message = e.getMessage();
        Log.i("1234", message + "::" + code);
    }

    @Override
    public void findSuccess(AddFriendsMessage requestAddFriendsMessage) {
        requestAddFriendsMessage.setMessage(mReason);
        Update.UpdateBmob(requestAddFriendsMessage.getObjectId(), requestAddFriendsMessage, AddFriendsActivity.this);
    }

    @Override
    public void findFailed(BmobException e) {
        AddFriendsMessage message = new AddFriendsMessage();
        message.setFrom(EMClient.getInstance().getCurrentUser());
        message.setTo(mUserName);
        message.setId(UUID.randomUUID().toString());
        message.setMessage(mReason);
        message.setState(0);
        message.setTime(SystemClock.currentThreadTimeMillis());
        new Thread(new Runnable() {
            @Override
            public void run() {
                Save.saveDataToBmob(message, AddFriendsActivity.this);
            }
        }).start();
    }

    @Override
    public void UpdateSuccess() {
        Toast.makeText(this, getResources().getString(R.string.add_chat_friends_remind_me), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void UpdateFailed() {

    }
}
